package com.lcx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcx.server.config.security.JwtTokenUtil;
import com.lcx.server.mapper.AdminMapper;
import com.lcx.server.mapper.AdminRoleMapper;
import com.lcx.server.mapper.RoleMapper;
import com.lcx.server.pojo.*;
import com.lcx.server.service.IAdminService;
import com.lcx.server.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Logan
 * @since 2021-12-03
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private AdminMapper adminMapper;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    /**
     * 登陆之后返回token
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password,String code, HttpServletRequest request) {

        //比对验证码
        String captcha = (String)request.getSession().getAttribute("captcha");
        System.out.println("222");
        if((code == null || "".equals(code)) || !captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码错误!");
        }


        //登陆验证
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        System.out.println("userDetails:"+userDetails);
        System.out.println("已加密"+userDetails.getPassword()+",未加密:"+password);
        if(null == userDetails || !passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码不正确!");
        }
        if(!userDetails.isEnabled()){
            return RespBean.error("账号被禁用,请联系管理员!");
        }
        System.out.println("更新用户信息之前");
        //更新security登陆用户对象 将用户信息更新到Principal
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        System.out.println("更新用户信息之后");
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> map = new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return RespBean.success("登陆成功",map);
    }


    /**
     * 根据用户名从数据库获取用户
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUsername(String username) {
        System.out.println("service...");
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username",username).eq("enabled",true);
        return adminMapper.selectOne(qw);
    }

    /**
     * 根据用户id查询角色列表
     * @param id
     * @return
     */
    @Override
    public List<Role> getRoles(int id) {

        return roleMapper.getRoles(id);
    }

    /**
     * 获取所有操作员信息(除了自己)
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);

    }


    /**
     * 更新操作员角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {

        //先清空该adminId下的角色
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
        //重新添加
        Integer result = adminRoleMapper.addAdminRole(adminId, rids);
        if (rids.length == result){
            return RespBean.success("更新成功!");
        }
        return RespBean.success("更新失败!");
    }

    /**
     * 更新用户密码
     * @param oldPass
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        //比对旧密码是否一致 一致才允许更新
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(passwordEncoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(passwordEncoder.encode(pass));
            int result = adminMapper.updateById(admin);
            if(1 == result){
                return RespBean.success("更新密码成功!");
            }
        }
        return RespBean.error("更新密码失败!");

    }


}
